<template>
  <div>
    <!--条件筛选-->
    <TopFilter ref="topFilter" :list="topFilterList" :cols="3" labelWidth="110" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>
    <!-- table -->
    <FilterTable
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :isSelectColumn="false"
      :onRowSelectChange="selectChange"
      :onColumnsChange="columns => this.columns = columns"
      :isExportExcel2="true"
      :exportFileName="'防盗码获取方式.xlsx'"
    >
      <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-plus" @click="detailHandle">新增</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="openimportPjDialog()">导入</el-button>
      </template>
    </FilterTable>

    <!-- 编辑窗口 -->
    <BaseDialog
      :visible.sync="visibleDrawer"
      :title="title"
      width="30%"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <add-obtain-mode v-model="initData" :type="handleType" :rowData="formData" @close="infoClose" />
    </BaseDialog>

    <BaseDialog style="min-height: 80vh;" :visible.sync="visibleImportPeij" width="80vw" title="导入" destroyOnClose
                :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '50px' }"
    >
      <ExcelImport
        ref="import"
        template-file-name="防盗码获取方式导入模板.xlsx"
        :importRules="importRules"
        :onComplete="importComplete"
        @close="visibleImportPeij = false"
      />
    </BaseDialog>
  </div>
</template>

<script>
  import { dictionary } from '@/utils/dictMixin';
  import {getSecurityCode,importVINObtain} from '@/api/customerService/SecurityCode/obtainMode/index';
  import {getAllUser} from '@/api/customerRepair/activityVisit/resultEntry/index';
  import addObtainMode from './addObtainMode';
  import ExcelImport from '@/components/ExcelImport';

  export default {
    name: "obtainMode",
    mixins: [dictionary],
    components: {addObtainMode,ExcelImport},
    data() {
      return{
        topFilterList: this.createTopFilterList(),
        columns: this.createTableColumns(),
        fetchApi: getSecurityCode,
        fetchParams: {xhrAbort: true},
        visibleDrawer: false,
        visibleImportPeij: false,
        handleType: '',
        formData: {},
        title: '',
        initData: {},
        rowSelectData: [],
        importRules: [
          {prop: 'attribute', title: '油电属性',
            rule: [
              { required: true, message: '油电属性不能为空' },
              {itemList: this.createDictList('5000')}
            ]},
          {prop: 'acquisitionMethod', title: '获取方式',
            rule: [
              { required: true, message: '获取方式不能为空' },
              {itemList: this.createDictList('5013')}
            ]
          },
        ]
      };
    },
    created() {
      this.getDictData();
    },
    methods: {
      async getDictData() {
        this.columns.find(x => x.dataIndex == 'attribute').dictItems = await this.createDictList('5000')
        this.columns.find(x => x.dataIndex == 'acquisitionMethod').dictItems = await this.createDictList('5013')
      },
      /* 打开导入配件Dialog */
      openimportPjDialog(){
        this.visibleImportPeij = true
      },
      //导入
      async importComplete(datas,callback){
        console.info(datas)
        const errorData = []
        datas.forEach((item, index1) => {
          const indexarr = []
          datas.forEach((i, index2) => {
            if (
              i.attribute === item.attribute &&
              index1 !== index2) {
              indexarr.push(index2 + 1)
            }
          })
          if (indexarr.length) {
            errorData.push({
              rownum: index1 + 1,
              errormsg: `与第${indexarr.join(',')}行信息重复`
            })
          }
        })
        if (errorData.length) {
          callback(errorData)
        } else {
          importVINObtain(datas).then(res => {
            if(res.resultCode == 200) {
              if(res.data.status){
                this.visibleImportPeij = false
                this.$notify.success({title: '提示信息', message: '批量导入成功'});
                callback()
                this.infoClose({type :"refresh"})
              }else{
                callback(res.data.errorData)
              }
            } else {
              callback([{errormsg: '服务器运行异常'}])
            }
          })
        }
      },
      createTopFilterList() {
        return[
          {
            type: 'SELECT',
            label: '油电属性',
            fieldName: 'attribute',
            placeholder: '请选择...',
            itemList: this.createDictList('5000')
          },
          {
            type: 'SELECT',
            label: '获取方式',
            fieldName: 'acquisitionMethod',
            placeholder: '请选择...',
            itemList: this.createDictList('5013')
          }
        ]
      },
      createTableColumns () {
        return [
          {
            title: '序号',
            dataIndex: 'index',
            width: 70,
            sorter: true,
            render: props => {
              return <span>{props.row.index + 1}</span>;
            }
          },
          {
            title: '操作',
            dataIndex: 'column-action',
            width: 70,
            fixed: 'left',
            render: props => {
              return (
                <div>
                <el-button size="mini" type="text" onClick={() => this.editHandle(props.row, 'edit')}>
              编辑
              </el-button>
              </div>
            );
            }
          },
          {
            title: '油电属性',
            dataIndex: 'attribute',
            sorter: true,
            // render: props => {
            //   return <span>{this.createDictText(props.row.attribute, '5000')}</span>;
            // }
          },
          {
            title: '获取方式',
            dataIndex: 'acquisitionMethod',
            sorter: true,
            // render: props => {
            //   return <span>{this.createDictText(props.row.acquisitionMethod, '5013')}</span>;
            // }
          },
          {
            title: '创建人',
            dataIndex: 'createUserInfo.userName',
            sorter: true,
          },
          {
            title: '创建时间',
            dataIndex: 'createdAt',
            dateFormat: 'yyyy-MM-dd HH:mm:ss',
            sorter: true,
          },
          {
            title: '修改人',
            dataIndex: 'updateUserInfo.userName',
            sorter: true,
          },
          {
            title: '修改时间',
            dataIndex: 'updatedAt',
            dateFormat: 'yyyy-MM-dd HH:mm:ss',
            sorter: true,
          }
        ]
      },
      selectChange(val) {
        console.log('val', val);
        if(val.length>0){
          console.info('111')
          this.isOpen=false;
          this.rowSelectData = val;
        } else {
          this.isOpen=true;
          this.rowSelectData = [];
        }
      },
      seacherFun(type){
        this.issearch = true
      },
      detailHandle(type) {
        this.title = '新增';
        this.handleType = 'add';
        this.initData = {
          type: type, // add-edit-show
          id: 1001
        }; //行id
        this.visibleDrawer = true;
      },
      editHandle(row, type) {
        if (type === 'edit') {
          this.title = '编辑';
        }
        this.formData = row;
        this.handleType = type;
        this.visibleDrawer = true;
      },
      changeHandle(val) {
        this.isOpen=true;
        this.fetchParams = Object.assign({}, val);
      },
      collapseHandle() {
        this.$nextTick(() => {
          this.BaseTable.EXECUTE_RESET_HEIGHT();
        });
      },
      infoClose(rData) {
        this.visibleDrawer = false;
        console.info(rData)
        if (rData.type === 'refresh') {
          // 重新加载
          this.fetchParams = { ...this.fetchParams };
        }
        // this.fetchParams = { ...this.fetchParams };
      },
    }
  }
</script>

<style scoped>

</style>
